/*
所有异步操作，比如用户登录或者登出，触发了调取Api或者读取本地数据库，都会触发App的重新渲染，这个文件就是用来做那些动作，
每个action都必须给出一个type来触发reducer，从而导致state发生变化
Exsample
export const login = () => ({
    type: types.LOGIN
})
*/
import * as types from './types'
import {AuthLoginApi, GetSettingsApi} from '../../config/api'
import Toast from 'react-native-root-toast/lib/Toast';
import store from '../store/store'

//判断本地是否登录
export const localLogin = () => {
    return dispatch => {
        return new Promise((resolve, reject) => {
            storage.load({
                key: 'user'
            }).then(user => {
                dispatch(loginSuccess(user))
                return resolve(true)
            }).catch(err => {
                dispatch(loginFailed())
                return resolve(false)
            })
        })
    }   
}

//登录
export const login = (username, password) => {
    return dispatch => {
        dispatch({type: types.LOGINING})
        AuthLoginApi(username, password).then((data) => {
            if (data.code == 0) {
                dispatch(loginSuccess(data))
                //登陆成功，获取配置
                dispatch(fetchSettings())
            } else {
                Toast.show(data.message)
                dispatch(loginFailed())
            }
        }).catch((err) => {
            Toast.show('网络错误')
            dispatch(loginFailed())            
        })
    }
}


export const changeRole = (isLeader) => {
    console.log(isLeader)
    return dispatch => {
        dispatch({type: types.CHANGEROLE,isLeader:isLeader})
    }
}

export const logout = () => {
    return dispatch => {
        //登出的时候清空数据
        dispatch({type: types.REFRESH_HOMEWORKS})
        dispatch({type: types.REFRESH_NOTIFICATIONS})
        storage.remove({
            key: 'user'
        });
        return dispatch({type: types.LOGOUT})       
    }
}

//登录成功
export const loginSuccess = (user) => {
    storage.save({
        key: 'user',
        data: user
    })
    Toast.show('登录成功')
    return {type: types.LOGIN_SUCCESS, user: user}
}

//登录失败
export const loginFailed = () => {
    return {type: types.LOGIN_FAILED}
}

export const fetchSettings = () => {
    return dispatch => {
        dispatch({type: types.FETCHING_SETTINGS})
        GetSettingsApi().then((data) => {
            if (data.code == 0) {
                dispatch({type: types.FETCH_SETTINGS_SUCCESS, settings: data})
            } else {
                Toast.show('获取设置信息失败，错误码:' + data.code)
                dispatch({type: types.FETCH_SETTINGS_FAIL})
            }
        }).catch((err) => {
            // Toast.show('网络错误')
        })
    }
}


